package com.atguigu.gulimall.ware.listener;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.OrderTo;
import com.atguigu.common.to.mq.StockDetailTo;
import com.atguigu.common.to.mq.StockLockedTo;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.atguigu.gulimall.ware.entity.WareOrderTaskEntity;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.vo.OrderVo;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @ClassName StockReleaseListener
 * @Description TODO
 * @Detail detail
 * @Author MyPC
 * @Date 2020/7/26
 * @Version 1.0
 */
@Service
@RabbitListener(queues = "stock.release.stock.queue")
public class StockReleaseListener {
    @Autowired
    WareSkuService wareSkuService;

    /**
     * 1、库存自动解锁
     *   下订单成功，库存也锁定成功，但是之后的操作出现异常，导致订单回滚，这种情况就要自动解锁库存
     * @param to
     * @param message
     */
    @RabbitHandler
    public void handleStockLockedRelease(StockLockedTo to, Message message, Channel channel) throws IOException {
        System.out.println("接收库存的消息：准备解锁库存");
        try{
            wareSkuService.unlockStock(to);
            //解锁成功，才能回复解锁成功的消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            //解锁异常，要拒绝消息，消息拒绝之后，重新放到队列中,让别人继续消费
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }

    /**
     * 订单关闭之后，也要进行锁定库存的释放
     * @param message
     * @param channel
     */
    @RabbitHandler
    public void handleOrderCloseRelease(OrderTo to,Message message, Channel channel) throws IOException {
        System.out.println("收到订单关闭消息，准备解锁库存");
        try{
            wareSkuService.unlockStock(to);
            //解锁成功，才能回复解锁成功的消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            //解锁异常，要拒绝消息，消息拒绝之后，重新放到队列中,让别人继续消费
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }
}
